import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper

class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "泰康悦行无忧两全保险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {

            # 年龄段
            "year": [str(i) for i in range(18, 51)],
            # 性别
            "gender": ["M", "F"],
            # 保障期限
            "expire": ["30年"],
            # 交费方式
            "payType": ["年交"],
            # 交费间隔
            "interval": ["0", "3", "5", "10"],
            # 保额
            "money": ["100000", "200000"],
            # 投保对象
            "payObject": ["本人"]

        }
        for v in product(plan["year"], plan["gender"], plan["expire"], plan["payType"], plan["interval"], plan["money"],
                         plan["payObject"]):
            if v[4] == "0":
                tuple_to_list = list(v)
                tuple_to_list[3] = "一次交清"
                list_to_tuple = tuple(tuple_to_list)

                data = Helper.formatProductInfo(plan, list_to_tuple)

            else:
                data = Helper.formatProductInfo(plan, v)
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {"calculateData": {
            "insuredInfo": [{"calinsuredRelationship": "01", "calinsuredBirth": "{0}-01-01".format( str(2020-int(dt["year"]))), "calinsuredGender": "1" if dt["gender"] == "M" else "2"}],
            "calpayPeriod": "SP" if dt["payType"] == "一次交清" else "Y" + dt["interval"], "calinsuredPeriod": "Y30", "planId": "1039", "calpayType": "SP" if dt["payType"] == "一次交清" else "Y",
            "planLiabilityList": [
                {"liabilityId": "5971", "amount": dt["money"], "liabilityName": "泰康悦行无忧两全保险", "liabilityAmount": "",
                 "premium": ""}], "calstartDate": "2020-04-02 00:00:00"},
                "exchangeData": {"memberId": "", "memberToken": "", "applicationId": "1245169842623373312",
                                 "applicationToken": "9d69f610b4541f84821699cb793156b7",
                                 "workqueueId": "973088997204410368", "channelId": "3"}}
        payload = json.dumps( data )
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and "保费试算成功" in r.text:
            price = Helper.decimalParse( r.json()["data"]["sumPremium"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)
